<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <!-- 搜索结果 列表-->
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        offset="30"
        @load="onLoad"
        v-if="ResultList.length > 0"
      >
        <article-item
          v-for="obj in ResultList"
          :key="obj.art_id"
          :ArticleObj="obj"
          :flag="false"
          @click.native="goArticle(obj.art_id)"
        ></article-item>
      </van-list>
      <!-- 搜索提示 -->
      <van-empty image="search" description="没有找到内容" v-else />
    </div>
  </div>
</template>

<script>
import { SearchResult } from '@/api/search/index.js'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  components: { ArticleItem },
  name: 'SearchResult',
  data() {
    return {
      searchresult: {
        q: this.$route.params.kw, // 搜索关键字
        page: 1, // 当前页码数
        per_page: 10, // 当前页需要的数据条数  不传默认10个
      },
      ResultList: [], // 搜索结果列表
      loading: false, // 上拉加载更多数据的状态
      finished: false, // 上拉加载 是否加载完毕
    }
  },
  created() {
    this.getResult()
  },
  methods: {
    // 获取搜索结果
    async getResult() {
      const { data: res } = await SearchResult(this.searchresult)
      if (res.message !== 'OK') {
        return this.$notify({ type: 'danger', message: '获取数据失败' })
      }
      if (res.data.results.length === 0) return (this.finished = true)
      this.ResultList = [...this.ResultList, ...res.data.results]
      // 加载状态结束
      this.loading = false
      this.searchresult.page++
    },
    // 上拉加载更多
    onLoad() {
      this.getResult()
    },
    // 去文章详情页
    goArticle(id) {
      this.$router.push({
        path: '/article_detail',
        query: { articleId: id },
      })
    },
  },
  comments: {
    ArticleItem,
  },
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
/deep/ .van-nav-bar__title {
  color: white;
}
</style>
